// mysql_cgi.cc
#include <iostream>
#include <string>
#include "mysql.h"
#include "comm.hpp"

bool InsertSql(std::string sql)
{
    MYSQL *conn = mysql_init(nullptr);
    mysql_set_character_set(conn, "utf8");

    if (nullptr == mysql_real_connect(conn, "127.0.0.1", "http_test", "12345678", "http_test", 3306, nullptr, 0))
    {
        std::cerr << "connect error." << std::endl;
        return 1;
    }
    std::cerr << "connect success." << std::endl;

    std::cerr << "query: " << sql << std::endl;
    int ret = mysql_query(conn, sql.c_str());
    std::cerr << "result: " << ret << std::endl;

    mysql_close(conn);
    return !ret;
}

int main()
{
    // get data from http
    std::string query_string;
    if (GetQueryString(query_string))
    {
        std::cerr << query_string << std::endl;
        // 数据处理
        std::vector<std::pair<std::string, std::string>> v;
        CutQueryString(v, query_string);

        std::string sql = "insert into user (name, passwd) values (\'";
        sql += v[0].second;
        sql += "\', \'";
        sql += v[1].second;
        sql += "\');";

        // 插入数据库
        if (InsertSql(sql))
        {
            std::cout << "<html><head><meta charset=\"UTF-8\"></head><body><h1>注册成功！</h1></body></html>";
        }
        else
        {
            exit(1);
        }
    }

    return 0;
}